<?php
namespace app\api\controller;

class VehicleOut extends Permission
{
    /** 
     * status 
     * 0 待审核
     * 10 财务审核
     * 20 领导审核
     * 30 不同意
     * 40 待付款
     * 50 财务审核
     * 60 付款失败
     * 100 完成
     * */
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = [];
        if( isset($this->input_data['status']) && $this->input_data['status'] != 99999999 ) $map['a.status'] = $this->input_data['status'];
        if( isset($this->input_data['cate']) && $this->input_data['cate'] != '不限' ) $map['a.cate'] = $this->input_data['cate'];

        if(isset($this->input_data['company']) && $this->input_data['company'] != '') $map['company'] = ['LIKE','%'.$this->input_data['company'].'%'];


        if($this->input_data['action'] == '内勤')
        {
            if($this->post('area_id') > 0)
            {
                $map['area_id'] = $this->post('area_id');
            }
            else
            {
                $map['area_id'] = ['IN',$this->myAllAreaIds];
            }
        }
        

        if(isset($this->input_data['plate_number']) && $this->input_data['plate_number'] !== '') $map['plate_number'] = ['LIKE','%'.$this->input_data['plate_number'].'%'];


        $total = db('VehicleOut')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($map)->count();
        $rows = db('VehicleOut')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number,b.reg_date,b.tel,b.realname,b.buy_price,b.buy_agent_fee,buy_other_fee,buy_images')->order('id', 'desc')->page($page,$limit)->where($map)->select();
        $list = [];
        foreach ($rows as $v) {
            $statusText = $this->_formatStatus($v);
            $v['statusText'] = $statusText['text'];
            $v['statusType'] = $statusText['type'];
            $v['amount'] = formatMoneyShow($v['amount']);
            $v['buy_agent_fee'] = formatMoneyShow($v['buy_agent_fee']);
            $v['buy_other_fee'] = formatMoneyShow($v['buy_other_fee']);
            $v['buy_price'] = formatMoneyShow($v['buy_price']);
            $v['finance_amount'] = formatMoneyShow($v['finance_amount']);
            $v['boss_amount'] = formatMoneyShow($v['boss_amount']);
            $v['paid'] = formatMoneyShow($v['paid']);
            $v['bill_amount'] = formatMoneyShow($v['bill_amount']);
            $list[] = $v;
        }

        $fJudge = $pay = $payJudge = 0;
        
        $rMap = $map;
        $rMap['a.status'] = 0;
        $fJudge = db('VehicleOut')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->where($rMap)->count();
        $rMap['a.status'] = 40;
        $pay = db('VehicleOut')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->where($rMap)->count();
        $rMap['a.status'] = 50;
        $payJudge = db('VehicleOut')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->where($rMap)->count();
        
        $badgeData = [
            'pay' => $pay,
            'payJudge' => $payJudge,
            'fJudge' => $fJudge,
        ];
        
        $data = [
            'total' => $total,
            'list' => $list,
            'map' => $map,
            'badgeData' => $badgeData
        ];
        $this->resSuc($data);
    }

    /** 
     * status 
     * 0 财务审核
     * 20 领导审核
     * 30 不同意
     * 40 待客户付款
     * 50 财务审核
     * 60 付款失败
     * 100 完成
     * */
    private function _formatStatus($v)
    {
        $type[0] = 'info';
        $type[20] = 'primary';
        $type[30] = 'danger';
        $type[40] = 'warning';
        $type[50] = 'info';
        $type[60] = 'danger';
        $type[90] = 'success';

        $text[0] = '待财务核算';
        $text[20] = '待领导核算';
        $text[30] = '领导不同意';
        $text[40] = '待客户付款';
        $text[50] = '付款待审核';
        $text[60] = '付款失败';
        $text[90] = '转出成功';


        $data = [
            'type' => $type[$v['status']],
            'text' => $text[$v['status']]
        ];

        return $data;
    }

    public function del()
    {
        $map = [
            'id' => $this->input_data['id'],
            'status' => 20
        ];
        if(db('VehicleOut')->where( $map )->find()) $this->resErr('无法删除已完成的收支');
        db('VehicleOut')->delete( $this->input_data['id']);
        
        $this->resSuc('ok');
    }

    public function update()
    {
        $data['vehicle_id'] = $this->input_data['vehicle_id'];
        $data['reason'] = $this->input_data['reason'];
        $data['save_option'] = $this->input_data['save_option'];
        $data['chat_images'] = $this->input_data['chat_images'];


        if($this->input_data['id'] > 0)
        {
            $data['id'] = $this->input_data['id'];
            db('VehicleOut')->update($data);
        }
        else
        {
            $id = db('VehicleOut')->insertGetId($data);
        }

        $this->resSuc('success');
    }

    public function getById()
    {
        $map['id'] = $this->input_data['id'];
        $result = db('VehicleOut')->where($map)->find();
        $this->resSuc($result);
    }
    // public function pay()
    // {
    //     $list = json_decode($this->input_data['list'],true);
    //     $names = [];
    //     $price = 0;
    //     foreach ($list as $v) {
    //         $names[] = $v['plate_number'];
    //         $price = bcadd($price, $v['amount']);
    //     }

    //     $names = implode(',', $names);
    //     $type = $list[0]['io_type'];
    //     $amount = $type == '支出' ? formatMoneySave($price * -1) : formatMoneySave($price);
    //     # 创建付款记录
    //     $data = [
    //         'cate' => '车辆收支',
    //         'type' => $type,
    //         'relation_id' => 0,
    //         'relation_name' => $names,
    //         'amount' => $amount,
    //         'create_user' => $this->user['realname'],
    //         'create_user_id' => $this->user['id'],
    //         'create_time' => time()
    //     ];
    //     // 支出就上传新的图片
    //     if($type == '支出'){
    //         $data['images'] = $this->input_data['images'];
    //     }
    //     else
    //     {
    //         // 收入就用提交上来的图片
    //         $data['images'] = $list[0]['images'];
    //     }


    //     $pay_record_id = db('PayRecord')->insertGetId($data);


    //     # 更新“车辆收支表的”信息
    //     # pay_user 支出的话表示谁付的款，收入的话表示谁审核的
    //     foreach ($list as $v) {

    //         $oData = [
    //             'id' => $v['id']
    //         ];
    //         if($type == '支出') $oData['pay_images'] = $this->input_data['images'];
            
    //         $oData['pay_user'] = $this->user['realname'];
    //         $oData['pay_user_id'] = $this->user['id'];
    //         $oData['pay_time'] = time();
    //         $oData['pay_record_id'] = $pay_record_id;
    //         $oData['status'] = 20;

    //         db('VehicleOut')->update($oData);
    //     }

    //     $this->resSuc('ok');
    // }

    // 审核转出价格
    public function judge()
    {
        $status = $this->_getJudgeStatus();
        $data = [
            'id' => $this->input_data['id'],
            'status' => $status,
            'finance_amount' => formatMoneySave($this->input_data['finance_amount']),
            'finance_result' => $this->input_data['finance_result'],
            'finance_reject_reason' => $this->input_data['finance_reject_reason'],
            'boss_amount' => formatMoneySave($this->input_data['boss_amount']),
            'boss_result' => $this->input_data['boss_result'],
            'boss_reject_reason' => $this->input_data['boss_reject_reason'],
        ];

        // 财务审核
        if($this->input_data['status'] == 0)
        {
            $data['finance_judge_time'] = time();
            $data['finance_judge_user'] = $this->user['realname'];
            $data['finance_judge_user_id'] = $this->user['id'];
        }
        // 领导审核
        if($this->input_data['status'] == 20)
        {
            if($this->input_data['boss_result'] == '同意')
            {
                // 领导同意的话，就按财务的价格
                $data['boss_amount'] = formatMoneySave($this->input_data['finance_amount']);
            }
            $data['boss_judge_time'] = time();
            $data['boss_judge_user'] = $this->user['realname'];
            $data['boss_judge_user_id'] = $this->user['id'];
        }

        db('VehicleOut')->update($data);

        $this->resSuc('ok');
    }
    private function _getJudgeStatus()
    {
        $status = 0;
        switch ($this->input_data['status']) {
            case 0:
                $status = 20; 
                break;
            case 20:
                $status = 40;
                break;
            
            default:
                // code...
                break;
        }
        return $status;
    }

    // 客户付款
    public function pay()
    {
        $map = [
            'id' => $this->input_data['id']
        ];
        $data = [
            'status' => 50,
            'paid' => formatMoneySave($this->input_data['paid']),
            'bill_amount' => formatMoneySave($this->input_data['bill_amount']), // 差价金额
            'diff_images' => $this->input_data['diff_images'],
            'diff_price_type' => $this->input_data['diff_price_type'],
            'pay_images' => $this->input_data['pay_images'],
            'grandfather' => $this->input_data['grandfather'], // 挂账人
            'bill_deadline' => $this->input_data['bill_deadline'],
            'pay_time' => time(),
            'pay_user' => $this->user['realname'],
            'pay_user_id' => $this->user['id']
        ];
        db('VehicleOut')->where($map)->update($data);

        $this->resSuc('ok');
    }

    private function _createBill($outId)
    {
        $out = db('VehicleOut')->where(['id'=>$outId])->find();

        # 生成账单主表
        $data = [
            'cate' => '挂账',
            'relation_id' => $outId,
            'vehicle_id' => $out['vehicle_id'],
            'amount' => $out['bill_amount'], // 本金
            'grandfather' => $out['grandfather'],
            'interest' => 0, // 利息
            'interest_rate' => 0, // 利率
            'times' => 1,
            'deadline' => $out['bill_deadline'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $bId = db('Bill')->insertGetId($data);
        # 生成账单明细
        $v['bill_id'] = $bId;
        $v['amount'] = $out['bill_amount'];
        $v['amount_total']  = $out['bill_amount'];
        $v['interest']  = 0;
        db('BillDetail')->insert($v);

    }

    // 客户付款
    public function judgePay()
    {
        $map = [
            'id' => $this->input_data['id']
        ];
        $data = [
            'status' => $this->input_data['status'],
            'judge_pay_time' => time(),
            'judge_pay_user' => $this->user['realname'],
            'judge_pay_user_id' => $this->user['id']
        ];
        db('VehicleOut')->where($map)->update($data);


        if( $this->input_data['status'] == 90 ){
            // 实付大于0 创建收入
            if($this->input_data['paid'] > 0) $this->_createPayRecord($this->input_data['id']);

            // 没付清 创建账单
            if($this->input_data['bill_amount'] * 1 > 0 && $this->input_data['diff_price_type'] == '挂账') $this->_createBill($this->input_data['id']);

            // 修改车辆状态
            $this->_updateVehicle($this->input_data['vehicle_id']);
        } 
        $this->resSuc('ok');
    }

    public function _updateVehicle($id)
    {
        $map = [
            'id' => $id
        ];
        $data = [
            'status' => '转出'
        ];
        db('Vehicle')->where($map)->update($data);
    }

    private function _createPayRecord($outId)
    {
        $out = db('VehicleOut')->where(['id'=>$outId])->find();
        $plateNumber = db('Vehicle')->where(['id'=>$out['vehicle_id']])->value('plate_number');
        # 创建付款记录
        $data = [
            'cate' => '车辆收支',
            'type' => '收入',
            'relation_id' => $outId,
            'relation_name' => $plateNumber,
            'amount' => $out['paid'],
            'images' => $out['pay_images'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time()
        ];
        $pay_record_id = db('PayRecord')->insertGetId($data);
    }

}
